﻿using CKS.Core.Framework;
using CKS.PLC.Core.Cache;
using FreeSql;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.System
{
    /// <summary>
    /// 
    /// 作用类型是加工结果，保存数据到1张表里
    /// </summary>
    public class SaveProcessingResults : PLCAction
    {
        public SaveProcessingResults(DecodeValue _value) : base(_value)
        {
        }


        public virtual void AfterSaved(CksCollected mainRecord)
        {

        }

        public override void Execute()
        {
            /*
                通用追溯
                根据点位关联的 PlcId\ActionId 查询到动作关联的表
             */

            var P = Value.Position;
            var act = conn.Select<CksPlcActions>().Where(a => a.ActionType == 1 && a.PlcId == P.PlcId && a.ActionId == P.ActionId && a.ActionKey == P.ActionKey  )
                .First();
            var table = conn.Select<CksVirtualTable>().Where(a => a.Id == act.BusinessId).First();
            var columns = conn.Select<CksVirtualColumn>().Where(a => a.TableId == act.BusinessId).OrderBy(a => a.Sequence).ToList();
            var replyPos = Value.GetReplyPosition(act.WriteDB, act.ActionId,act.ActionKey);
            var result = Value.Value.ToInt();
            if (result == 1)
            {
                string triggerNo = $"{Guid.NewGuid().ToString("N")}"; // 触发编号
                //获取分组情况

                var maxLocation = Value.GetMaxLocation();
                if (maxLocation == 0)
                {
                    CksCollected cl = SaveDataRecord(act, table, columns, triggerNo, 0);
                }
                else
                {
                    for (int i = 1; i <= maxLocation; i++)
                    {
                        CksCollected cl = SaveDataRecord(act, table, columns, triggerNo, i);
                    }
                }




                //回复保存完成信号
                WriteInt16(replyPos, 1);
                //EventBus.AddLog($"模块：数据采集；工站：{SiemensClient.PlcInfo.WorkstationCode};保存-{cl.SequenceId}-{cl.PrimaryCode}");
            }
            else if (result == 0)
            {
                //复位上位机的信号
                WriteInt16(replyPos, 0);
                EventBus.AddLog($"{SiemensClient.PlcInfo.PlcAddress} 模块：数据采集；信号：{replyPos.Address};重置");
            }


        }

        private CksCollected SaveDataRecord(CksPlcActions act, CksVirtualTable table, List<CksVirtualColumn> columns, string triggerNo, int location)
        {
            string batchNo = $"{Guid.NewGuid().ToString("N")}"; // 数据批次
            table.MaxSeqId = GetNextSeq(table); //获取当前表格的最大虚拟Id
            List<CksCollectedDetails> details = new List<CksCollectedDetails>();
            CksCollected cl = new CksCollected()
            {
                BatchCode = batchNo,
                BatchSuffix = GetSuffix(batchNo, 5),
                CreatedTime = DateTime.Now,
                PlcId = act.PlcId,
                SequenceId = table.MaxSeqId,
                TableId = table.Id,
                LocationId = location,
            };


            //遍历采集项
            string mainCode = string.Empty;
            foreach (var item in columns)
            {
                var decodeObject = Value.GetLinkDecodeData(location, item.DataId);

                string content = decodeObject.IsCharArray? decodeObject.CharString:decodeObject.Value.ToString();
                var model = new CksCollectedDetails()
                {
                    Content = content,
                    ColumnName = item.ColumnName,
                    ColumnId = item.Id,
                    PlcId = act.PlcId,
                    TableId = table.Id,
                    BatchSuffix = GetSuffix(batchNo, 5),
                    BatchCode = batchNo,
                    CreatedTime = cl.CreatedTime
                };

                if (item.IsPrimary)
                {
                    cl.PrimaryCode = content;
                    mainCode = content;
                    cl.Suffix_4 = GetSuffix(content);
                }
                if (item.IsResult)
                    cl.Result = content.ToInt();

                details.Add(model);
            }
            if (!mainCode.IsEmpty())
            {
                conn.Insert(details).ExecuteAffrows();
                conn.Insert(cl).ExecuteAffrows();
                conn.Update<CksVirtualTable>().SetSource(table)
                    .UpdateColumns(a => a.MaxSeqId).ExecuteAffrows();

                AfterSaved(cl);//
            }
            return cl;
        }

        /// <summary>
        /// 内置序列
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        private long GetNextSeq(CksVirtualTable table)
        {
            var n = conn.Select<CksVirtualTable>().Where(a => a.TableName == table.TableName).First();
            return n.MaxSeqId + 1;
        }

       

    }
}
